// pages/lottery/box.js
const Utils = require('../../utils/utils');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    banner_image_loading: true,
    lottery_id: '',
    show_code_dialog: false, // 抽奖提示 - 提醒输入抽奖码
    show_update_dialog: false, // 完善领奖人信息提示
    lotteryCode: '', // 抽奖码
    honoree_name: '', // 领奖人名字
    honoree_telephone: '', // 领奖人手机号
    honoree_room_no: '', // 领奖人房间号
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { lottery_id } = options;
    if (!lottery_id) {
      wx.showModal({
        title: '提示',
        content: '无效的活动 id',
        showCancel: false,
        confirmText: '返回首页',
        success: res => {},
      });
      return;
    }
    this.setData({ lottery_id });
    // wx.showLoading({ title: '加载中' });
    this.fetchLotteryDetail(lottery_id).then(res => {
      // wx.hideLoading();
      this.setData({ loading: false });
    }).catch(err => {
      console.error('onLoad fetchLotteryDetail', err);
      wx.showToast({ title: '业务异常', icon: 'error' });
    });
  },

  /**
   * banner 图片加载完成
   */
  bannerImageLoadedAction: function() {
    this.setData({ banner_image_loading: false });
  },

  /**
   * 获取抽奖活动详情
   * @param {String} lottery_id 抽奖活动 id
   */
  fetchLotteryDetail: function(lottery_id) {
    const paramsData = {
      params: { lottery_id },
      action: 'FetchDetail'
    };
    const promise = wx.cloud.callFunction({ name: 'boxLottery', data: paramsData }).then(({ result }) => {
      const { award } = result.data;
      console.log(result.data);
      this.setData({ lottery: result.data, award });
      return result.data;
    });
    return promise;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 输入抽奖码弹框 - 取消
   */
  onCodeDialogCancel: function() {
    this.setData({ show_code_dialog: false, lotteryCode: '' });
  },

  /**
   * 输入抽奖码弹框 - 确认
   */
  onCodeDialogConfirm: function() {
    const { lottery_id, lotteryCode, userInfo } = this.data;
    if (!lotteryCode) {
      wx.showToast({ title: '请填写抽奖码', icon: 'none' });
      return false;
    }

    this.setData({ show_code_dialog: false, lotteryCode: '' });
    Utils.requestSubscribeMessage(this.data.lottery.tmplIds)
    .then(res => {
      console.log(res);
      // 调用参与抽奖函数
      wx.showLoading({ title: '请稍等' })
      const paramsData = {
        params: { lottery_id, lottery_code: lotteryCode, user_info: userInfo },
        action: 'ParticipateAction'
      };
      return wx.cloud.callFunction({ name: 'boxLottery', data: paramsData });
    })
    .then(res => {
      const { code, errmsg } = res.result;
      if (code !== 0) {
        wx.showToast({ title: errmsg, icon: 'error' });
      } else {
        wx.showToast({ title: '参与成功', icon: 'success' });
        // 刷新当前页面
        wx.startPullDownRefresh();
      }
    })
    .catch(err => {
      console.error('BoxLottery ParticipateAction', err);
      wx.showToast({ title: '业务异常', icon: 'error' });
    });
  },

  /**
   * 参与抽奖
   * 1. 点击按钮弹出抽奖码输入弹框
   * 2. 输入抽奖码，点击确定提醒订阅消息, 并提交当前用户信息参与成功
   */
  participateAction: function({ detail = {} }) {
    console.log('detail', detail.userInfo);
    const userInfo = detail.userInfo;
    this.setData({ show_code_dialog: true, lotteryCode: '', userInfo });
  },

  /**
   * 去领奖
   * @param {*} res res
   */
  takePrizeAction: function(res) {
    const { lottery } = this.data;
    this.setData({ show_update_dialog: true });
    // 调用函数获取领奖人信息
    const paramsData = {
      params: { lottery_id: lottery._id },
      action: 'FetchHonoreeInfoAction'
    };
    wx.cloud.callFunction({ name: 'boxLottery', data: paramsData }).then(res => {
      console.log(res.result);
      const { code, errmsg, data } = res.result;
      if (code === 0) {
        this.setData({ honoree_name: data.name || '', honoree_telephone: data.telephone || '', honoree_room_no: data.room_no || '' });
      } else {
        throw { code, errmsg }
      }
    }).catch(err => {
      console.error('BoxLottery FetchHonoreeInfoAction Error', err);
    });
  },

  /**
   * 完善中奖人提示框-取消
   */
  onUpdateDialogCancel: function() {
    this.setData({ show_update_dialog: false });
  },

  /**
   * 完善中奖人提示提示框-确定
   */
  onUpdateDialogConfirm: function() {
    const { honoree_name, honoree_telephone, honoree_room_no, lottery, award } = this.data;
    if (!honoree_name) {
      wx.showToast({ title: '请输入姓名', icon: 'error'});
      return;
    }
    if (!honoree_telephone) {
      wx.showToast({ title: '请输入手机号', icon: 'error'});
      return;
    }
    const phoneReg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (!phoneReg.test(honoree_telephone)) {
      wx.showToast({ title: '手机号不正确', icon: 'error'});
      return;
    }
    if (!honoree_room_no) {
      wx.showToast({ title: '请输入房间号', icon: 'error'});
      return;
    }
    const honoree = {
      lottery_id: lottery._id,
      name: honoree_name,
      telephone: honoree_telephone,
      room_no: honoree_room_no,
      ...lottery.winner,
      award
    };
    console.log(honoree);
    // 提交领奖人信息
    wx.showLoading({ title: '提交中...' });
    const paramsData = {
      params: honoree,
      action: 'CommitHonoreeInfoAction'
    };
    wx.cloud.callFunction({ name: 'boxLottery', data: paramsData }).then(res => {
      const { code, errmsg } = res.result;
      if (code !== 0) throw { code, errmsg };
      this.setData({ show_update_dialog: false });
      wx.showToast({ title: '提交成功', icon: 'success' });
    }).catch(err => {
      console.error('onLotteryDialogConfirm Error', err);
      wx.showToast({ title: err.errmsg || '网络异常', icon: 'error' });
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const { lottery_id } = this.data;
    this.fetchLotteryDetail(lottery_id).then(res => {
      wx.stopPullDownRefresh()
    }).catch(err => {
      wx.stopPullDownRefresh()
      console.error('onLoad fetchLotteryDetail', err);
      wx.showToast({ title: '业务异常', icon: 'error' });
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const { lottery, award, lottery_id } = this.data;
    const path = `/pages/lottery/box?lottery_id=${lottery_id}`;
    const shareInfo = {
      title: lottery.name,
      path,
      imageUrl: award.pic
    };
    return shareInfo;
  }
})